package demoMod.stsconsole.helpers;

import demoMod.stsconsole.dungeons.AbstractDungeon;
import demoMod.stsconsole.potions.AbstractPotion;
import demoMod.stsconsole.potions.FirePotion;

import java.util.*;
import java.util.stream.Collectors;

public class PotionLibrary {
    private static final Map<String, Class<? extends AbstractPotion>> potions = new HashMap<>();
    private static final List<AbstractPotion> potionCache = new ArrayList<>();

    public static void initialize() {
        potions.clear();
        potions.put(FirePotion.ID, FirePotion.class);
    }

    public static AbstractPotion getPotion(String id) {
        try {
            return potions.getOrDefault(id, FirePotion.class).newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return new FirePotion();
    }

    public static AbstractPotion getPotion(Random rng, AbstractPotion.PotionRarity rarity) {
        if (potionCache.isEmpty()) {
            try {
                for (Map.Entry<String, Class<? extends AbstractPotion>> e : potions.entrySet()) {
                    potionCache.add(e.getValue().newInstance());
                }
            } catch (InstantiationException | IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
        List<AbstractPotion> potionList = potionCache.stream().filter(potion -> (AbstractDungeon.player.getPotionColor() == potion.color || potion.color == AbstractPotion.PotionColor.SHARED)
                && potion.rarity == rarity).collect(Collectors.toList());
        Collections.shuffle(potionList, rng);
        if (potionList.isEmpty()) {
            return new FirePotion();
        }
        return potionList.get(0).makeCopy();
    }
}
